package com.mingtu.dzpatrol.activity;

import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.media.MediaScannerConnection;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hikvision.formatconversion.HikFormatConversion;
import com.hikvision.hatomplayer.DefaultHatomPlayer;
import com.hikvision.hatomplayer.HatomPlayer;
import com.hikvision.hatomplayer.PlayCallback;
import com.hikvision.hatomplayer.PlayConfig;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.dzpatrol.R;
import com.mingtu.dzpatrol.base.BaseActivity;
import com.mingtu.dzpatrol.callback.StringDialogCallback;
import com.mingtu.dzpatrol.decoration.GridSpacingItemDecoration;
import com.mingtu.dzpatrol.utils.Constant;
import com.mingtu.dzpatrol.utils.MyLogUtil;
import com.mingtu.dzpatrol.utils.PlayMusicUtils;
import com.mingtu.hikvideo2.adapter.HikFucAdapter;
import com.mingtu.hikvideo2.utils.PlayerStatus;
import com.mingtu.hikvideo2.utils.RecordTimeUtils;
import com.mingtu.hikvideo2.view.RockerView;
import com.mingtu.hikvideo2.widget.window.PlayTextureView;

import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;

public class NewPreviewActivity extends BaseActivity implements TextureView.SurfaceTextureListener, SurfaceHolder.Callback {

    private String url;
    private RecyclerView hikRecycle;
    private HatomPlayer hatomPlayer;
    private PlayTextureView playTextureView;
    private TextView zoomText;
    private ProgressBar loadingView;
    private TextView errorText;
    private LinearLayout layoutRecordTime;
    private TextView tvRecordTime;
    private RecordTimeUtils recordTimeUtils;
    private CheckBox checkBoxTop;
    private CheckBox checkBoxRight;
    private CheckBox checkBoxDown;
    private CheckBox checkBoxleft;
    private String command;
    private int action;
    private String cameraIndexCode;
    private long formatHandle = 0L;
    private boolean isRecording = false;
    private PlayerStatus mPlayerStatus = PlayerStatus.IDLE;//默认闲置
    private String TAG = "VideoPlay";
    private HikFucAdapter hikFucAdapter;
    private CheckBox checkZoom;
    private LinearLayout layoutZoom;
    private LinearLayout layoutControll;
    private FrameLayout layoutTexture;
    private LinearLayout layout;
    private ImageView ivBackLandscape;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private boolean flag;
    private LinearLayout layoutSurface;
    private Canvas canvas;
    private int surfaceWidth;
    private int surfaceHeight;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_preview_new;
    }

    @Override
    protected void initView() {
//        getTopLeftButton().setImageResource(R.mipmap.icon_back_white);
//        setModuleTitleColor(R.color.white);
//        setTitleBarBackground(getResources().getColor(R.color.black));

        //沉侵式状态栏
        ImmersionBar immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(true);
        immersionBar.autoStatusBarDarkModeEnable(true);
//        immersionBar.barColor(R.color.black);
        immersionBar.init();

        ivBackLandscape = (ImageView) findViewById(R.id.iv_back_landscape);
        ivBackLandscape.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkZoom.setChecked(false);
                ScreenUtils.setPortrait(NewPreviewActivity.this);
                layoutViews();
            }
        });
        playTextureView = (PlayTextureView) findViewById(R.id.textureView);
        zoomText = (TextView) findViewById(R.id.zoomText);
        errorText = (TextView) findViewById(R.id.errorText);
        loadingView = (ProgressBar) findViewById(R.id.loadingView);
        hikRecycle = (RecyclerView) findViewById(R.id.hikRecycle);
        layoutRecordTime = (LinearLayout) findViewById(R.id.layout_record_time);
        tvRecordTime = (TextView) findViewById(R.id.tv_record_time);
        RockerView rockerView = (RockerView) findViewById(R.id.rocker_view);
        checkBoxTop = (CheckBox) findViewById(R.id.checkbox_top);
        checkBoxRight = (CheckBox) findViewById(R.id.checkbox_right);
        checkBoxDown = (CheckBox) findViewById(R.id.checkbox_down);
        checkBoxleft = (CheckBox) findViewById(R.id.checkbox_left);
        checkZoom = (CheckBox) findViewById(R.id.check_zoom);
        layoutZoom = (LinearLayout) findViewById(R.id.layout_zoom);
        layoutControll = (LinearLayout) findViewById(R.id.layout_controll);
        layoutTexture = (FrameLayout) findViewById(R.id.layout_texture);
        layout = (LinearLayout) findViewById(R.id.layout);
        surfaceView = (SurfaceView) findViewById(R.id.surface_view);
        layoutSurface = (LinearLayout) findViewById(R.id.layout_surface);
        initSurfaceView();

        layoutZoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isChecked = checkZoom.isChecked();
                int maxHeight = 0;
                if (isChecked) {
                    //缩小
                    checkZoom.setChecked(false);
                    ScreenUtils.setPortrait(NewPreviewActivity.this);
                    layoutViews();
                } else {
                    //放大
                    checkZoom.setChecked(true);
                    ScreenUtils.setLandscape(NewPreviewActivity.this);
                    layoutViews();
                }
            }
        });

        rockerView.setCallBackMode(RockerView.CallBackMode.CALL_BACK_MODE_STATE_CHANGE);
        rockerView.setOnShakeListener(RockerView.DirectionMode.DIRECTION_8, new RockerView.OnShakeListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void direction(RockerView.Direction direction) {
                MyLogUtil.e("direction", "摇动方向 : " + getDirection(direction));
                action = 0; //开始
                PTZControlling();

            }

            @Override
            public void onFinish() {
                setCheckBox(0);
                action = 1; //停止
                PTZControlling();
            }
        });


        playTextureView.setSurfaceTextureListener(this);

        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);//第二个参数为网格的列数
        hikRecycle.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(10), true));
//        recycler.setHasFixedSize(true);
        hikRecycle.setLayoutManager(layoutManager);

        hikFucAdapter = new HikFucAdapter(context);
        hikRecycle.setAdapter(hikFucAdapter);
        hikFucAdapter.setOnItemClickListener(new HikFucAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                boolean b = hikFucAdapter.getCheckEvent(position);
                if (position == 0) {
                    //抓拍
                    capture();
                } else if (position == 1) {
                    //录像
                    startRecord();
                    hikFucAdapter.setCheckEvent(position, !b);
                } else if (position == 2) {
                    //3D放大
                    if (b) {
                        layoutSurface.setVisibility(View.GONE);
                    } else {
                        layoutSurface.setVisibility(View.VISIBLE);
                    }
                    hikFucAdapter.setCheckEvent(position, !b);
                }


            }
        });
        storagePermissions();
    }

    @Override
    protected void initData() {
        url = getIntent().getStringExtra("videoUrl");
        String title = getIntent().getStringExtra("title");
        cameraIndexCode = getIntent().getStringExtra("code");
        setModuleTitle(title);
        if (StringUtils.isEmpty(url)) {
            ToastUtils.showLong("未获取到播放链接哦~");
            return;
        }
        if (StringUtils.isEmpty(cameraIndexCode)) {
            ToastUtils.showLong("未获取到监控点编号哦~");
            return;
        }

        surfaceWidth = ScreenUtils.getScreenWidth();
        surfaceHeight = SizeUtils.dp2px(250f);
    }

    @Override
    protected void getData() {

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (hatomPlayer != null) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //开启预览
                    //此方法需要在子线程中执行
                    hatomPlayer.stop();
                }
            }).start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (hatomPlayer != null) {
            //Waited 5000ms for KeyEvent(action=UP))
            new Thread(new Runnable() {
                @Override
                public void run() {
                    hatomPlayer.pause();
                }
            }).start();

        }
        if (isRecording) {
            //正在录制的时候关闭录制
            stopRecordResult();
        }

        if (playTextureView.isAvailable()) {
            onSurfaceTextureDestroyed(playTextureView.getSurfaceTexture());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (hatomPlayer != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    hatomPlayer.resume();
                }
            }).start();
        }
        if (playTextureView != null) {
            if (playTextureView.isAvailable()) {
                onSurfaceTextureAvailable(playTextureView.getSurfaceTexture(), playTextureView.getWidth(), playTextureView.getHeight());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (playTextureView != null) {
            if (playTextureView.isAvailable()) {
                playTextureView.setSurfaceTextureListener(null);
                onSurfaceTextureDestroyed(playTextureView.getSurfaceTexture());
            }
        }
        if (isRecording == true) {
            //正在录制的时候关闭录制
            stopRecordResult();
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {

        if (mPlayerStatus == PlayerStatus.STOPPING) {
            //恢复处于暂停播放状态的窗口
            startPreview();
            MyLogUtil.e(TAG, "onSurfaceTextureAvailable: startRealPlay");
        } else if (mPlayerStatus == PlayerStatus.IDLE) {
            startPreview();
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        if (mPlayerStatus == PlayerStatus.SUCCESS) {
            mPlayerStatus = PlayerStatus.STOPPING;//暂停播放，再次进入时恢复播放
            stopPlay();
            MyLogUtil.e(TAG, "onSurfaceTextureDestroyed: stopPlay");
        }
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
//        Thread t = new Thread(this); // 创建一个线程对象
//        // 把线程运行的标识设置成true
//        flag = true;
//        t.start(); // 启动线程

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        flag = false;
    }

    private int startX = 0;
    private int startY = 0;
    private int endX = 0;
    private int endY = 0;

    private void initSurfaceView() {
        surfaceView.setZOrderOnTop(true);//处于顶层
        surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);//设置surface为透明
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        layoutSurface.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 记录触摸点坐标
                        startX = x;
                        startY = y;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // 计算偏移量
                        endX = x;
                        endY = y;
                        // 在当前left、top、right、bottom的基础上加上偏移量
                        doDraw(startX, startY, endX, endY);
                        MyLogUtil.e("testtest", "ACTION_MOVE======" + startX + "," + startY + "," + endX + "," + endY);
                        break;
                    case MotionEvent.ACTION_UP:
                        clearDraw();

                        MyLogUtil.e("testtest", "ACTION_UP======" + surfaceWidth + "," + surfaceHeight);
                        MyLogUtil.e("testtest", "========" + startX + "," + startY + "," + endX + "," + endY);

                        int sX = (startX * 255 / surfaceWidth);
                        int sY = (startY * 255 / surfaceHeight);
                        int eX = (endX * 255 / surfaceWidth);
                        int eY = (endY * 255 / surfaceHeight);

                        PTZSelZoom(sX, sY, eX, eY);
                        break;

                }


                return true;
            }
        });
    }

    /**
     * 画框
     */
    private void doDraw(int left, int top, int right, int bottom) {
        //定义画笔
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        // mpaint.setAntiAlias(true);//去锯齿
        paint.setStyle(Paint.Style.STROKE);//空心
        // 设置paint的外框宽度
        paint.setStrokeWidth(4f);


        canvas = surfaceHolder.lockCanvas();
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); //清楚掉上一次的画框。
        Rect r = new Rect(left, top, right, bottom);
        canvas.drawRect(r, paint);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }

    /**
     * 清除画布
     */
    public void clearDraw() {

        try {
            canvas = surfaceHolder.lockCanvas(null);
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
            surfaceHolder.unlockCanvasAndPost(canvas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 停止播放
     */
    private void stopPlay() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //开启预览
                //此方法需要在子线程中执行
                if (hatomPlayer != null) {
                    hatomPlayer.stop();
                }
            }
        }).start();

    }

    /**
     * 抓拍
     */
    private void capture() {
        if (mPlayerStatus == PlayerStatus.SUCCESS) {
            if (hatomPlayer != null) {
                PlayMusicUtils.playSound(NewPreviewActivity.this, "SnapShot.mp3");
                String savePath = PathUtils.getExternalPicturesPath();
                String fileName = TimeUtils.getNowMills() + ".jpg";
                String path = savePath + "/" + fileName;
                int isSave = hatomPlayer.screenshot(path, "");
                if (isSave == 0) {
                    //扫描更新媒体库(图库相册)
                    MediaScannerConnection.scanFile(NewPreviewActivity.this, new String[]{savePath}, null, null);
                    ToastUtils.showLong("抓拍成功！已保存到相册");

//                    try {
//                        MediaStore.Images.Media.insertImage(context.getContentResolver(), path, fileName, null);
//                        ToastUtils.showLong("抓拍成功！");
//                    } catch (FileNotFoundException e) {
//                        ToastUtils.showLong("抓拍失败！");
//                        e.printStackTrace();
//                    }
//                    // 最后通知图库更新
//                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(path))));
                }
            }
        } else {
            ToastUtils.showLong("没有视频在播放,不能抓拍哦~");
        }
    }

    /**
     * 开始录像
     */
    private void startRecord() {
        if (mPlayerStatus == PlayerStatus.SUCCESS) {
            if (hatomPlayer != null) {
                String savePath = PathUtils.getExternalMoviesPath();
                String fileName = TimeUtils.getNowMills() + ".mp4";
                final String path = savePath + "/" + fileName;
                if (!isRecording) {
                    //计时
                    recordTimeUtils = new RecordTimeUtils(tvRecordTime);
                    //重新开始巡护的的时间逻辑
                    recordTimeUtils.setTime(0);
                    recordTimeUtils.startTimer();

                    hatomPlayer.setPreRecordCallback(new PlayCallback.PreRecordCallback() {
                        @Override
                        public int onPreRecord(int dataType, byte[] bytes, int length) {
                            //开始录制
                            layoutRecordTime.setVisibility(View.VISIBLE);

                            if (dataType == PlayCallback.PreRecordCallback.STREAM_HEAD) {
                                //流头
                                long createHandle = HikFormatConversion.createHandle();
                                if (createHandle == -1L) {
                                    return -1;
                                }
                                formatHandle = createHandle;
                                if (!HikFormatConversion.start(formatHandle, bytes, path)) {
                                    HikFormatConversion.stop(formatHandle);
                                    HikFormatConversion.destroyHandle(formatHandle);
                                    return -1;
                                }
                                return 0;
                            } else if (dataType == PlayCallback.PreRecordCallback.STREAM_DATA) {
                                //数据
                                boolean result = HikFormatConversion.inputSourceData(formatHandle, bytes, length);
                                return result ? 0 : -1;
                            } else {
                                //结束
                                HikFormatConversion.stop(formatHandle);
                                HikFormatConversion.destroyHandle(formatHandle);
                                return 0;
                            }
                        }
                    });
                    int result = hatomPlayer.startRecord(path);
                    if (result == 0) {
                        isRecording = true;
                    }
                } else {
                    //正在录制的时候关闭录制
                    if (stopRecordResult() == 0) {
                        ToastUtils.showLong("录制成功！已保存到相册");
                        MediaScannerConnection.scanFile(context, new String[]{savePath}, null, null);
                    } else {
                        ToastUtils.showLong("录制失败！");
                    }
                }
            }
        } else {
            ToastUtils.showLong("没有视频在播放,不能录像哦~");
        }
    }

    /**
     * 结束录像
     */
    private int stopRecordResult() {
        int result = 0;
        try {
            result = hatomPlayer.stopRecord();
            if (result == 0) {
//                hikFucAdapter.setRecordCheck(false);
                isRecording = false;
            }
            if (recordTimeUtils != null) {
                recordTimeUtils.stopTimer();
            }
            layoutRecordTime.setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 开始预览
     */
    private void startPreview() {
        loadingView.setVisibility(View.VISIBLE);
        //创建HatomPlayer实例
        hatomPlayer = new DefaultHatomPlayer();
        playTextureView.setOnZoomListener(new PlayTextureView.OnZoomListener() {
            @Override
            public void onZoomChange(Rect oRect, Rect curRect) {
                hatomPlayer.openDigitalZoom(oRect, curRect);
            }
        });

        final DecimalFormat decimalFormat = new DecimalFormat("0.0");
        //设置电子放大倍率监听
        playTextureView.setOnZoomScaleListener(new PlayTextureView.OnZoomScaleListener() {
            @Override
            public void onZoomScale(float scale) {
                if (scale < 1.0f) {
                    //如果已经开启了电子放大且倍率小于1就关闭电子放大
                    hatomPlayer.closeDigitalZoom();
                }
                if (scale >= 1.0f) {
                    String text = MessageFormat.format("{0}X", decimalFormat.format(Double.valueOf(scale + "")));
                    zoomText.setText(text);
                }

            }
        });


        SurfaceTexture surfaceTexture = playTextureView.getSurfaceTexture();
        hatomPlayer.setSurfaceTexture(surfaceTexture);

        //播放前设置播放配置(可选)
        PlayConfig playConfig = new PlayConfig();
        playConfig.hardDecode = true;//使用硬解码
        playConfig.privateData = false;//关闭智能信息
        hatomPlayer.setPlayConfig(playConfig);
        hatomPlayer.setDataSource(url, null);
        hatomPlayer.setPlayStatusCallback(new PlayCallback.PlayStatusCallback() {
            @Override
            public void onPlayerStatus(@NonNull PlayCallback.Status status, final String error) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingView.setVisibility(View.GONE);
                    }
                });

                if (status == PlayCallback.Status.SUCCESS) {//播放成功
                    mPlayerStatus = PlayerStatus.SUCCESS;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            errorText.setVisibility(View.GONE);
                            playTextureView.setKeepScreenOn(true);//保持亮屏
                        }
                    });
                } else if (status == PlayCallback.Status.FAILED) {//播放失败
                    mPlayerStatus = PlayerStatus.FAILED;

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            errorText.setVisibility(View.VISIBLE);
                            errorText.setText("预览失败，" + error);
                        }
                    });

                } else if (status == PlayCallback.Status.EXCEPTION) {//取流异常
                    mPlayerStatus = PlayerStatus.EXCEPTION;
                    stopPlay();//TODO 注意:异常时关闭取流
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            errorText.setVisibility(View.VISIBLE);
                            errorText.setText("取流异常,预览失败，" + error);
                        }
                    });
                }


            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                //开启预览
                //此方法需要在子线程中执行
                hatomPlayer.start();
            }
        }).start();
    }

    /**
     * 云台控制
     */
    private void PTZControlling() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("cameraIndexCode", cameraIndexCode);
        hashMap.put("action", action);
        hashMap.put("command", command);
        hashMap.put("speed", 80);
        String str = GsonUtils.toJson(hashMap);

        OkGo.<String>post(Constant.getInstance().POST_PTZ_CONTROLL)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                        }
                    }
                });
    }

    /**
     * 监控点3D放大
     *
     * @param
     */
    private void PTZSelZoom(int sX, int sY, int eX, int eY) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("cameraIndexCode", cameraIndexCode);
        hashMap.put("startX", sX);
        hashMap.put("startY", sY);
        hashMap.put("endX", eX);
        hashMap.put("endY", eY);
        String str = GsonUtils.toJson(hashMap);

        OkGo.<String>post(Constant.getInstance().POST_PTZ_SEL_ZOOM)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                        }
                    }
                });
    }

    private void setCheckBox(int i) {
        if (i == 1) { //上
            checkBoxTop.setChecked(true);
            checkBoxRight.setChecked(false);
            checkBoxDown.setChecked(false);
            checkBoxleft.setChecked(false);
        } else if (i == 2) { //右
            checkBoxTop.setChecked(false);
            checkBoxRight.setChecked(true);
            checkBoxDown.setChecked(false);
            checkBoxleft.setChecked(false);
        } else if (i == 3) {//下
            checkBoxTop.setChecked(false);
            checkBoxRight.setChecked(false);
            checkBoxDown.setChecked(true);
            checkBoxleft.setChecked(false);
        } else if (i == 4) {//左
            checkBoxTop.setChecked(false);
            checkBoxRight.setChecked(false);
            checkBoxDown.setChecked(false);
            checkBoxleft.setChecked(true);
        } else if (i == 0) {
            checkBoxTop.setChecked(false);
            checkBoxRight.setChecked(false);
            checkBoxDown.setChecked(false);
            checkBoxleft.setChecked(false);
        } else if (i == 12) {//右上
            checkBoxTop.setChecked(true);
            checkBoxRight.setChecked(true);
            checkBoxDown.setChecked(false);
            checkBoxleft.setChecked(false);
        } else if (i == 32) {//右下
            checkBoxTop.setChecked(false);
            checkBoxRight.setChecked(true);
            checkBoxDown.setChecked(true);
            checkBoxleft.setChecked(false);
        } else if (i == 14) {//左上
            checkBoxTop.setChecked(true);
            checkBoxRight.setChecked(false);
            checkBoxDown.setChecked(false);
            checkBoxleft.setChecked(true);
        } else if (i == 34) {//左下
            checkBoxTop.setChecked(false);
            checkBoxRight.setChecked(false);
            checkBoxDown.setChecked(true);
            checkBoxleft.setChecked(true);
        }
    }

    private String getDirection(RockerView.Direction direction) {
        String message = null;
        switch (direction) {
            case DIRECTION_LEFT:
                message = "左";
                setCheckBox(4);
                command = "LEFT";
                break;
            case DIRECTION_RIGHT:
                message = "右";
                setCheckBox(2);
                command = "RIGHT";
                break;
            case DIRECTION_UP:
                message = "上";
                setCheckBox(1);
                command = "UP";
                break;
            case DIRECTION_DOWN:
                message = "下";
                setCheckBox(3);
                command = "DOWN";
                break;
            case DIRECTION_UP_LEFT:
                message = "左上";
                setCheckBox(14);
                command = "LEFT_UP";
                break;
            case DIRECTION_UP_RIGHT:
                message = "右上";
                setCheckBox(12);
                command = "RIGHT_UP";
                break;
            case DIRECTION_DOWN_LEFT:
                message = "左下";
                setCheckBox(34);
                command = "LEFT_DOWN";
                break;
            case DIRECTION_DOWN_RIGHT:
                message = "右下";
                setCheckBox(32);
                command = "RIGHT_DOWN";
                break;
            default:
                break;
        }
        return message;
    }

    /**
     * 屏幕方向变化后重新布局View
     */
    private void layoutViews() {
        int screenWidth = ScreenUtils.getScreenWidth();
        ViewGroup.LayoutParams layoutParams = layoutTexture.getLayoutParams();
        if (ScreenUtils.isPortrait()) {
//            int height = ScreenUtils.getScreenHeight() - StatusBarUtil.getStatusBarHeight(context) - SizeUtils.dp2px(10);
            int height = ScreenUtils.getScreenHeight();
            layoutParams.height = height;
            layoutParams.width = (int) (height / 0.618);

            layoutControll.setVisibility(View.GONE);
            layout.setBackgroundColor(context.getResources().getColor(R.color.black));
            hideHeadView();
            ivBackLandscape.setVisibility(View.VISIBLE);
            BarUtils.setStatusBarVisibility(this, false);

            surfaceWidth = (int) (height / 0.618);
            surfaceHeight = height;

        } else if (ScreenUtils.isLandscape()) {
            layoutParams.height = SizeUtils.dp2px(250f);
            layoutParams.width = screenWidth;

            layoutControll.setVisibility(View.VISIBLE);
            layout.setBackgroundColor(context.getResources().getColor(R.color.main_bg));
            showHeadView();
            ivBackLandscape.setVisibility(View.GONE);
//            statusBarView.setVisibility(View.VISIBLE);
            BarUtils.setStatusBarVisibility(this, true);

            surfaceWidth = screenWidth;
            surfaceHeight = SizeUtils.dp2px(250f);
        }

        layoutTexture.setLayoutParams(layoutParams);
    }

    public void storagePermissions() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            new XPopup.Builder(NewPreviewActivity.this)
                                    .isDestroyOnDismiss(true)
                                    .dismissOnTouchOutside(true)
                                    .hasShadowBg(true)
                                    .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_storage_auth),
                                            context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                            new OnConfirmListener() {
                                                @Override
                                                public void onConfirm() {
                                                    XXPermissions.startPermissionActivity(NewPreviewActivity.this, permissions);
                                                }
                                            }, null, false)
                                    .show();
                        } else {

                        }

                    }
                });
    }


}